// miniprogram/pages/editView/personalCenter/activityHeXiao.js
var requestManager = require('../../../utils/requestManager.js')
var util = require('../../../utils/util.js')
var hxActivityId = ''
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isBoss: true,
    scrollHeight: 0,
    peepleCount: 0,
    passwordManagement: '',
    selectIndex: -1,
    selectId: '',
    hidden: true,                  // 控制弹框
    modalInputValue: '',           // 记录输入框的值
    searchText: '',
    applyPeopleList: [],
    nextUrl: '',
    shopImage: '',
    isFirstLoad: false,
    password: '',                  // 口令 (员工的情况用到)
    isShowPasswordModal: false,     // 展示口令输入框 (员工的情况用到)       
    shop_id:"",
    share_shop_id:""
  },

  /////////////// 公有方法 ///////////////
  /** 
   * 将网络请求活动数据转化成UI需要的数据模型数组
   */
  resArrayConverToObjectList: function (resArray, dataArray) {
    for (var i = 0; i < resArray.length; i++) {
      let dic = resArray[i]
      let createTime = util.formatUTCDateByFormatStr(dic["create_time"], 'YYYY-MM-DD HH:mm')
      let tDic = {
        'id': dic['id'],
        'userId': dic['userId'],
        'name': dic['nick'],
        'phone': dic['phone'],
        'time': createTime,
        'hexiaoed': dic['has_used'],
        'mark': dic['remarks']
      }
      dataArray.push(tDic);
    }
  },
  /////////////// 公有方法 ///////////////


  /////////////// 网络请求 ///////////////
  /** 
   * 用户报名列表
   * activityId 活动id
   * searchText 搜索条件（手机号）
   */
  requestApplyPeopleList: function (activityId, searchText) {
    var that = this
    let url = 'apply/people/list?id=' + activityId
    var search = false
    if (searchText&&searchText.length > 0) {
      // 搜索的情况
      search = true;
      url += '&select=' + searchText
    }
    requestManager.getRequest(url, {} , function(res) {
      let status = res.status
      if (status == 0) {
        let array = res.results
        var applyPeopleArray = []
        that.data.nextUrl = res.next
        // 将网络请求活动数据转化成UI需要的数据模型数组
        that.resArrayConverToObjectList(array, applyPeopleArray)
        // 更新UI
        if (!that.data.isFirstLoad) {
          // 第一次请求 需要判断用户角色
          that.setData({
            isFirstLoad: true,
            isBoss: app.globalData.owner,
            isShowPasswordModal: !(app.globalData.owner),
            passwordManagement: res['command'],
            shopImage: res['shop_image'],
            shop_id: res.shop_id,
            shop_title: res.shop_title
          })
        }
        that.setData({
          peopleCount: res['applly_people_number'],
          applyPeopleList: applyPeopleArray,
          shop_id: res.shop_id
        })
      } 
    })
  },

  /** 
   * 核销用户
   * applyId 报名人id
   * selectIndex 当前选中数据的对应下标
   */
  requestHeXiaoApplyPeople: function (applyId, selectIndex) {
    var that = this
    let hexiaoed = this.data.applyPeopleList[selectIndex].hexiaoed
    // 网络请求 核销用户
    requestManager.postRequest('apply/people/sign?people_id=' + applyId, {}, function (res) {
      let status = res.status
      if (status == 0) {
        // 网络请求成功 改变数组里面的数据
        wx.showToast({
          title: '核销用户成功！',
          icon: 'none',
          success:function(){
            let key = 'applyPeopleList[' + selectIndex + '].hexiaoed'
            that.setData({
              [key]: !hexiaoed
            })
          }
        })
      }
    })
  },

  /**
   * 添加备注
   * applyId 报名人id
   * remarks 备注内容
   */
  requestMark: function (applyId, mark) {
    var that = this
    requestManager.postRequest('apply/people/remarks?people_id=' + applyId, { 'remarks': mark }, function (res) {
      let status = res.status
      if (status == 0) {
        // 添加备注成功
        let mark = that.data.modalInputValue
        let key = 'applyPeopleList[' + that.data.selectIndex + '].mark'
        that.setData({
          [key]: mark,
          selectId: '',
          modalInputValue: '',
          selectIndex: -1
        })
      }
    })
  },

  /**
   * 上拉加载请求
   */
  requestNextApplyPeopleList: function (nextUrl) {
    var that = this
    console.log('nextUrl' + nextUrl)
    let hasff = 'https://wx.extend.xuemei99.com/'
    let next = nextUrl.substring(hasff.length)

    requestManager.getRequest(next, {}, function (res) {
      let status = res.status
      if (!that.data.hideBottom) {
        that.setData({
          hideBottom: true
        })
      }
      if (status == 0) {
        that.data.nextUrl = res.next
        // 更新UI
        if (that.data.isSearch) {
          // 搜索的时候
          var applyPeopleArray = that.data.searchList
          // 将网络请求活动数据转化成UI需要的数据模型数组
          that.resArrayConverToObjectList(array, applyPeopleArray)
          that.setData({
            searchList: applyPeopleArray
          })
        } else {
          var applyPeopleArray = that.data.applyPeopleList
          // 将网络请求活动数据转化成UI需要的数据模型数组
          that.resArrayConverToObjectList(array, applyPeopleArray)
          that.setData({
            applyPeopleList: applyPeopleArray
          })
        }
      }
    })
  },

  /**
   * 口令验证
   */
  requestVerifyPassword: function (activityId, password) {
    let that = this
    requestManager.postRequest('apply/little/apply/product/command?id=' + activityId, {'command': password}, function (res) {
      let status = res.status
      if (status == 0) {
        wx.showToast({
          title: '验证通过',
          success:function(){
            that.setData({
              isShowPasswordModal: false
            })
          }
        })
      }
    })
  },

  /////////////// 网络请求 ///////////////

  /////////////// 事件 ///////////////
  /* 核销 */
  hexiaoTap: function (event) {
    let id = event.currentTarget.dataset.id;
    let index = event.currentTarget.dataset.index;
    let hexiaoed = event.currentTarget.dataset.hexiaoed;
    if (hexiaoed == false) {
      this.requestHeXiaoApplyPeople(id, index)
    }
  },

  /* 电话 */
  phoneTap: function (event) {
    let phone = event.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },

  /* 备注 */
  markTap: function (event) {
    let mark = event.currentTarget.dataset.mark
    let index = event.currentTarget.dataset.index
    let id = event.currentTarget.dataset.id   
    this.setData({
      selectId: id,
      modalInputValue: mark,
      selectIndex: index,
      hidden: false
    });
  },

  cancel: function () {
    this.setData({
      selectId: '',
      modalInputValue: '',
      selectIndex: -1,
      hidden: true
    });
  },

  confirm: function () {
    var that = this
    this.setData({
      hidden: true
    });
    let applyId = this.data.selectId;
    let mark = this.data.modalInputValue
    this.requestMark(applyId, mark)
  },

  // 搜索tap
  searchTap: function (event) {
    // 判断输入的是否是手机号
    // 验证手机号
    var that = this
    let reg = /1[\d]{10}/;
    let phone = this.data.searchText
    if (!phone) {
      wx.showToast({
        title: '请填写手机号！',
        icon: 'none'
      })
      return;
    }
    if (!reg.test(phone)) {
      wx.showToast({
        title: '请填写正确的手机号！',
        icon: 'none'
      })
      return;
    }
    
    this.requestApplyPeopleList(hxActivityId, that.data.searchText)  
  },

  // 输入框监控
  modalInput: function (event) {
    this.data.modalInputValue = event.detail.value
  },

  searchInput: function (event) {
    this.data.searchText = event.detail.value
    if(this.data.searchText < 1) {
      this.requestApplyPeopleList(hxActivityId)
    }
  },

  /**
   * 口令监听（员工的情况）
   */
  passwordInput: function (event) {
    this.data.password = event.detail.value
  },

  /** 
   * 确认输入的口令（员工的情况）
   */
  passwordConfirm: function (event) {
    this.requestVerifyPassword(hxActivityId, this.data.password)
  },

  /** 
   * 下拉刷新
   */
  scrollToupper: function (event) {
    console.log('下拉刷新')
    this.requestApplyPeopleList(hxActivityId)
  },

  /** 
   * 上拉加载
   */
  scrollTolower: function (event) {
    console.log('上拉加载')
    let tNextUrl = this.data.nextUrl
    if (tNextUrl && tNextUrl.length > 0) {
      this.requestNextApplyPeopleList(tNextUrl)
    }
  },
  /////////////// 事件 ///////////////

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log(options)
    if (options.shop_id) {//转发进入
      console.log("有shop_id")
      app.globalData.shop_id = options.shop_id//更新shop_id
      hxActivityId = options.activity_id
      that.requestApplyPeopleList(hxActivityId)
    }else{//点击页面进入
      console.log(options)
      hxActivityId = options.activity_id
      that.requestApplyPeopleList(hxActivityId)
    }
    
    // 设置scroll-view的高度
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight: res.windowHeight - 105 - 64
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉刷新')
    this.requestApplyPeopleList(hxActivityId)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // console.log('上拉加载')
    // let tNextUrl = this.data.nextUrl
    // if (tNextUrl && tNextUrl.length > 0) {
    //   this.requestNextApplyPeopleList(tNextUrl)
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    let that = this;
    if (options.from == 'button') {
      console.log(this.data.shopImage)
    }
    return {
      path: '/pages/editView/personalCenter/activityHeXiao?activity_id=' + hxActivityId + '&shop_id=' + that.data.shop_id,
      title: "微报名活动核销",
      imageUrl: that.data.shopImage,
      success: function (res) {
        console.log(that.data.shop_id)
        //这是我自定义的函数，可替换自己的操作
        wx.showToast({
          title: '分享成功',
          icon: 'none'
        })
      },
      fail: function () {
        wx.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    }
  }
})